﻿using System;
using Ninject;
using Ninject.Modules;
using Ninject.Web;
using NLog;
using OBoobsWallpaper.Configuration;
using OBoobsWallpaper.Logic;

namespace OBoobsWallpaper
{
    public class InfrastructureModule :  NinjectModule
    {
        public override void Load()
        {
            #region Configuration

            Bind<IRssCacheConfig>().To<Config>(); //TODO: Use only one instance
            Bind<IRssLoaderConfig>().To<Config>();
            Bind<IRssManagerSchedulerConfig>().To<Config>();

            #endregion

            Bind<IRssLoader>().To<OBoobsRssLoader>();
            Bind<RssManagerScheduler>().ToSelf().InSingletonScope();
            Bind<IRssManager>().To<RssManager>();
            Bind<IRssCache>().To<RssCache>();
        }
    }

    public class Global : NinjectHttpApplication
    {
        [Inject]
        public RssManagerScheduler RassRssManagerScheduler { get; set; }
        private static readonly Logger Logger = LogManager.GetCurrentClassLogger();

        protected override void OnApplicationStarted()
        {
            Logger.Info("Web application is starting...");
            RassRssManagerScheduler.Start();
            Logger.Info("Web application was started");
        }

        protected override void OnApplicationEnded()
        {
            Logger.Info("Web application is stopping...");
            RassRssManagerScheduler.Stop();
            Logger.Info("Web application was stoped");
        }

        protected void Application_Error(object sender, EventArgs e)
        {
            var exception = Server.GetLastError();
            Logger.FatalException("Unhandled exception was caught", exception); //TODO: Make NLog log exception
        }

        protected override IKernel CreateKernel()
        {
            return new StandardKernel(new InfrastructureModule());
        }
    }
}